/*异步日志缓冲区*/

#ifndef __M_BUFF_H__
#define __M_BUFF_H__

#include "util.hpp"
#include <vector>
#include <cassert>

namespace Alpaca
{
#define DEFAULT_BUFFER_SIZE (1 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (8 * 1024 * 1024)
#define INCREASE_BUFFER_SIZE (1 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer()
            : _buffer(DEFAULT_BUFFER_SIZE),
              _read_idx(0), _write_idx(0) {}

        void push(const char *data, size_t len)
        {
            //将是否扩容的决定权交给用户,因此这里只扩容
            ensureEnoughSize(len);

            std::copy(data, data + len, &_buffer[_write_idx]);

            // 将可写位置向后偏移
            MoveWriter(len);
        }

        const char *begin() // 返回可读数据的起始地址
        {
            return &_buffer[_read_idx];
        }

        size_t ReadAbleSize()
        {
            return (_write_idx - _read_idx);
        }
        size_t WriteAbleSize()
        {
            return (_buffer.size() - _write_idx);
        }

        void MoveReader(size_t len)
        {
            assert(len <= ReadAbleSize());
            _read_idx += len;
        }
        void MoveWriter(size_t len)
        {
            assert(len + _write_idx <= _buffer.size());
            _write_idx += len;
        }

        void reset()
        {
            _write_idx = 0;
            _read_idx = 0;
        }

        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(buffer._read_idx, _read_idx);
            std::swap(buffer._write_idx, _write_idx);
        }

        bool empty()
        {
            return (_read_idx == _write_idx);
        }

    private:
        void ensureEnoughSize(size_t len)
        {
            if (len < WriteAbleSize())
                return;
            size_t newsize = 0;
            while (newsize < len)
            {
                if (_buffer.size() < THRESHOLD_BUFFER_SIZE)
                    newsize = _buffer.size() * 2;
                else
                    newsize = _buffer.size() + INCREASE_BUFFER_SIZE;
            }

            _buffer.resize(newsize);
        }

    private:
        std::vector<char> _buffer;
        size_t _read_idx;
        size_t _write_idx;
    };
}

#endif